/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


//fungsi untuk mengupdate
var username = "anis";
window.friend="";
//register timer
window.timerArray= new Array();
//register yang sedang aktif
//nama friend atau room yang sedang aktif
window.activeFriendOrRoom="";
//tipe chat yang sedak aktif, apakah room atau friend
window.tipeActive="";
//kategori yang sedang aktif
window.currentCategory="";
//variabel initialize
window.timer1;
window.timer2;
window.onload = update(username);
window.chatlist;
window.counter;
//window.onload = updateChatTab(username);

function getxmlhttp()
{
    try {
        //If the javascript version is greater than 5.
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        //If not, then use the older active x object.
        try {
            //If we are using Internet Explorer.
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            //Else we must be using a non-IE browser.
            xmlhttp = false;
        }
    }
    //If we are using a non-IE browser, create a javascript instance of the object.
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function processajax(serverpage,object,getorpost,str,readyfunction,tipeXML)
{
    var obj;
    if(typeof object == "string" ){        
        obj = document.getElementById(object);
    }
    else
        obj = object;
    var xmlhttp = getxmlhttp();
   
    if(getorpost == "get"){
        xmlhttp.open("GET",serverpage);
        
        xmlhttp.onreadystatechange = function(){            
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                if(object=="rooms"){
                        var doc2 = document.getElementById(object);
                        if(doc2!=null){
                            doc2.innerHTML=xmlhttp.responseText;
                        }
                 }
                if(obj!=null){                    
                    if(readyfunction != null){
                        if(!tipeXML)
                            readyfunction(obj,xmlhttp.responseXML);
                        else
                            readyfunction(obj,xmlhttp.responseText);
                    }
                    else{                        
                        obj.innerHTML = xmlhttp.responseText;
                    }
                }
                else{
                    
                }
            }
            else{
                standardFunction(xmlhttp, object);
            }
        }
        xmlhttp.send(null);
    }
    else{
        xmlhttp.open("POST", serverpage, true);
        //alert(serverpage);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF8");
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                obj.innerHTML = xmlhttp.responseText;
            }
            else{
                standardFunction(xmlhttp, object);
            }
        }
        xmlhttp.send(str);
    }
}

function standardFunction(xmlhttp,object){
//do nothing
}

function update(username){
    updateFriend();
    updateChatTab();
    loadRoom();
    deleteAllFriend();
    updateRoom();
}

function loadRoom(){
    processajax("functions/roomJSP.jsp?task=loadRoom", "rooms", "get", null, null, null);
    updateRoom();
}

function updateRoom(){
    processajax("functions/roomJSP.jsp?task=update", "rooms", "get", null, null);
    setTimeout('updateRoom()', 3000);
}

function deleteAllFriend(){
    processajax("functions/process.jsp?task=deletefriend", "dump", "get",null,null);
}

function updateFriend(){
    processajax("functions/process.jsp?task=updateFriends", "friends", "get", null);
    setTimeout('updateFriend();', 5000);
}

function updateChatTab(){
    
    processajax("functions/xmlchat.jsp", "chat_tab", "get", null,readyFunctionChatTab)
    setTimeout('updateChatTab()', 5000);
}

function getformvalue(fobj)
{
    var str="";
    var i=0;
    while((i<fobj.elements.length))
    {
        str += fobj.elements[i].name +"="+escape(fobj.elements[i].value)+"&";
        i++;
    }
    return str;
}

function submitform(theform,serverpage,objid,evt){
    var str=getformvalue(theform);
    //alert('masuksini');
    //alert(str);
    start = true;
    processajax(serverpage, objid, "post", str,evt);

}

function enterpressed(e,theform){
    var charCode;

    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        handleSubmit(theform);
        document.getElementById("chat_input").value="";
    }
}

function handleSubmit(theform){
    var str = document.getElementById("chat_input").value;
    var objid,tipe;
    if(str.length>2 && str[0]=='/'){
        var str2 = str.substr(1, str.length);
        var hasil = str.split(" ");
        tipe="command";
        if(hasil[0] == "/addfriend"){
            objid = "friends";
           if(hasil[1]==""){
                alert("wrong command; required friend name");
                return;
            }
        } else if(hasil[0] == "/create"){
            alert(hasil[1]);
            objid = "rooms";            
            if(window.currentCategory=="" || hasil[1]==""){
                alert("wrong command; required room name and you must select a category first!!");
                return;
            }
        } else if(hasil[0] == "/join"){
            if(hasil[1] == ""){
                alert("Wrong Command; required roomname");
                return;
            }
            addChatTab(hasil[1], "room");
        } else if(hasil[0] == "/chat"){
            if(hasil[1] ==""){
                alert("Wrong Command; required friend name");
                return;
            }
            
        } 
        
    }
    else{
        //sedang chatting
        objid = "chat_area";
        tipe="chat";
    }
    if(tipe=="chat"){
        if(window.tipeActive=="" ||window.activeFriendOrRoom==""){
            alert("Please Choose Room Or Friend")
        }
        else
            processajax("functions/process.jsp?task=processCommand&&tipe="+tipe+"&&tipechat="+window.tipeActive+"&&nama="+window.activeFriendOrRoom, objid, "post", getformvalue(theform));
    }
    else
    {        
        processajax("functions/process.jsp?task=processCommand&&tipe="+tipe+"&&tipechat="+window.tipeActive+"&&nama="+window.activeFriendOrRoom+"&&category="+window.currentCategory, objid, "post", getformvalue(theform));
    }
}

//chat dengan friend
function addChatTab(username,tipe){
    //cek apakah sudah ada timernya
    if(window.timerArray[username]!=null){
        return;
    }
    var doc = document.getElementById("chat_tab");
    var docno = document.getElementById("noavailable");
    if(docno!=null){
        doc.removeChild(docno);
    }
    var childnodearray = doc.childNodes;
    var jumlah = childnodearray.length;
    //alert(jumlah);
    var newdiv = document.createElement("div");
    newdiv.setAttribute("class", "chattab");
    newdiv.setAttribute("id", username);
    newdiv.innerHTML=username;
    doc.appendChild(newdiv);
    //pindahkan tab active ke yang sekarang
    moveChat(username, tipe);
    //daftarkan listener
    newdiv.addEventListener("click", function(){
        moveChat(username, tipe)
    },true);
    //daftarkan update chat
    window.timerArray[username] = window.setTimeout("updateChat('"+username+"','"+tipe+"')",2000);
    //daftarkan yang sedang aktif
    window.activeFriendOrRoom = username;
    //daftarkan tipe yang sedang aktif
    window.tipeActive=tipe;
    //masukkan ke daftar orang yang lagi chatting
    if(tipe=="friend")
        processajax("functions/chatprocess.jsp?task=addchatfriend&&username="+username, "dump", "get", null, null);
    else
        processajax("functions/roomJSP.jsp?task=addchatroom&&username="+username, "dump", "get", null, null);

}

function moveChat(username,tipe){
    window.activeFriendOrRoom = username;
    window.tipeActive = tipe;
    window.timerArray[username] = window.setTimeout("updateChat('"+username+"','"+tipe+"')",2000);
    obj = document.getElementById(username);
    if(obj)
        obj.style.backgroundImage = "url(images/tab-bg.png)";
}

function updateChat(username,tipe){
    
        if(window.activeFriendOrRoom == username)
            processajax("functions/chatStart.jsp?task=updateTab&&tipe="+tipe+"&&status=active&&friend="+username, "chat_area", "get", null,null);
        else
            processajax("functions/chatStart.jsp?task=updateTab&&tipe="+tipe+"&&status=passive&&friend="+username, username, "get",null, passive,"text");
        
        window.timerArray[username] = window.setTimeout("updateChat('"+username+"','"+tipe+"')",2000);
    
}

function passive(obj,hasil){
    //alert(hasil);
    if(hasil.indexOf("@update@", 0)!=-1){
        obj.style.backgroundImage = "url(images/tab-bg-update.png)";
    }
}

function readyFunctionChatTab(obj,hasil){
    var doc = document.getElementById("chat_tab");
    var docno = document.getElementById("noavailable");
    //hasil=trim(hasil);
    if(docno!=null){
        doc.removeChild(docno);
    }
    //hasilarray = hasil.split("\\s+");
    var childNodes = doc.childNodes;
    var i;    
    window.chatlist = new Array();
    window.chatlist = hasil.getElementsByTagName("chatfriend");
    window.counter=0;
    
    // alert(chatlist.length);
    for(window.counter=0;window.counter<window.chatlist.length;window.counter++){
        var newdiv = document.createElement("div");
        newdiv.setAttribute("class", "chattab");
        newdiv.setAttribute("id", window.chatlist[window.counter].firstChild.data);
        newdiv.innerHTML=window.chatlist[window.counter].firstChild.data;
        var a = function(ec){
            moveChat(ec, "friend");
        };
        newdiv.addEventListener("click",function(e){
            a(this.id);
        } ,false);
     
        window.timerArray[chatlist[counter].firstChild.data.toString()] = window.setTimeout( "updateChat('"+chatlist[counter].firstChild.data+"','friend');", 1000);
        //setTimeout( "updateChat("+chatlist[counter].firstChild.data.toString()+",friend);", 1000);
        doc.appendChild(newdiv);
    }
    
     
    
}


/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/* ROOM AREA */
function showHideDiv(object){
    var doc = document.getElementById(object);
    var doc2 = document.getElementById(object+"_images");
    if(doc!=null && doc2!=null){
        if(doc.style.visibility=="hidden"){
            doc.style.visibility="visible";
            doc.style.height = "auto";
            doc2.src = "images/min.png";
            processajax("functions/roomJSP.jsp?task=vision&&status=visible&&catname="+object, "dump", "get", null, null);
        }
        else{
            doc.style.visibility="hidden";
            doc.style.height = "0px";
            doc2.src = "images/plus.png";
            processajax("functions/roomJSP.jsp?task=vision&&status=hidden&&catname="+object, "dump", "get", null, null);
        }


    }
}

function updateKategori(){
    processajax("functions/roomJSP.jsp?task=updateKat", "rooms", "get", null, null, null);
    setTimeout('updateKategori()', 10000);
}

function chooseCategory(categoryname){
    window.currentCategory=categoryname;
    alert("You're now in category " + window.currentCategory);
}
